<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/5/22
 * Time: 18:04
 */
namespace App\Http\Controllers\Api\User;

use App\Http\Controllers\Api\WeChatControllerBase;
use App\Http\Controllers\Controller;
use App\Libs\TencentCloud\FaceIdentify;
use App\Modules\System\Services\DictionaryService;
use App\Modules\User\Models\UserCertification;
use App\Modules\User\Services\UserService;
use App\Modules\User\Services\UserTaskDetailService;
use Hashids;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

use Illuminate\Support\Facades\Log;

class UserController extends Controller {
    /**
     * 同意用户服务协议
     * @param Request $request
     */
    public function service_protoc(Request $request) {
        $uid = $this->getLoginUserId();
        $user_info = UserService::getById($uid);
        $user_info->is_agree_protoc =1;
        $user_info->save();
    }

    /**
     * 绑定手机号
     * @param Request $request
     * @return mixed
     */
    public function bind_phone(Request $request) {
        $session_key = $request->input('session_key','');
        $encryptedData = $request->input('encrypted_data','');
        $iv = $request->input('iv','');
        $app =WeChatControllerBase::initInstance();
        $decryptedData = $app->encryptor->decryptData($session_key, $iv, $encryptedData);
        if(empty($decryptedData)||!isset($decryptedData['phoneNumber'])||empty($decryptedData['phoneNumber'])) {
            return response()->error('DECRYPT_FAIL');
        }
        $phone = $decryptedData['phoneNumber'];
        $uid = $this->getLoginUserId();
        if(empty($phone)) {
            return response()->error('PARAM_EMPTY');
        }
        $user_info_by_uid = UserService::getById($uid);
        $user_info_by_phone = UserService::getUserInfoByPhone($phone);
        \DB::beginTransaction();
        try{
            if($user_info_by_phone && ($user_info_by_phone->id != $uid)) {
                UserService::deleteOne($uid);
                $user_info_by_phone->openid = $user_info_by_uid->openid;
                $user_info_by_phone->target_value = DictionaryService::getDictionary('target')->value;
                $user_info_by_phone->save();
            }else{
                $user_info_by_uid->phone = $phone;
                $user_info_by_uid->target_value = DictionaryService::getDictionary('target')->value;
                $user_info_by_uid->save();
            }
            \DB::commit();
        }catch (\Exception $e) {
            \Log::error(__FUNCTION__.$uid.$e->getMessage());
            \DB::rollback();
            return response()->error('BIND_ERROR');
        }
        return response()->success();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function getUserProfile(Request $request) {
        $uid = $this->getLoginUserId();
        $user_info = UserService::getById($uid);
        if($user_info && $user_info->phone) {
            $user_info->is_bind_phone = 1;
        }else if($user_info){
            $user_info->is_bind_phone = 0;
        }
        //unset($user_info->id);
        $user_info->id = \Hashids::encode($user_info->id);
        unset($user_info->phone);
        return response()->success($user_info);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function setHeightOrWeight(Request $request) {
        $uid = $this->getLoginUserId();
        $height = $request->input('height','');
        $weight = $request->input('weight','');
        if(empty($height) && empty($weight)) {
            return response()->error('PARAM_EMPTY');
        }
        $user_info = UserService::getById($uid);
        if($height) {
            $user_info->height = $height;
        }
        if($weight) {
            $user_info->weight = $weight;
        }
        $user_info->save();
        return response()->success();
    }

    /**
     * 获取faceID
     * @param Request $request
     * @return mixed
     */
    public function getFaceId(Request $request) {
        $id_card = $request->input('id_no','');
        $name = $request->input('name','');
        $face_identy = new FaceIdentify();
        $trade_no = date('YmddHis').hexdec(uniqid());
        $wbappid = env('TENCENT_FACE_APPID');
        $licence = env('TENCENT_FACE_LICENCE');
        $uid = $this->getLoginUserId();
        //var_dump($uid);
        $uid = Hashids::encode($uid);
        //var_dump($uid);
        //var_dump(Hashids::decode($uid)[0]);
        $nonceStr = $face_identy->getNonceStr();
        $res = $face_identy->uploadUserInfo($trade_no,$name,$id_card,$uid,$nonceStr);
        if($res == false) {
            return response()->error('GET_FACEID_FAILED');
        }
        $face_id = $res['faceId'];
        $biz_seq = $res['bizSeqNo'];
        $sign = $res['sign'];
        UserCertification::create(compact('trade_no','uid','id_card','name','biz_seq'));
        return response()->success(compact('id_card','name','face_id','biz_seq','nonceStr','uid','sign','trade_no','wbappid','licence'));
    }

    /**
     *
     * @param Request $request
     * @return mixed
     */
    public function upFaceIdentifyResult(Request $request) {
        $is_success = $request->input('is_success',-1);
        $img = $request->file('image_source');
        //$best_frame_path = $request->input('image_source','');
        $uid = $this->getLoginUserId();
        $trade_no = $request->input('order_no','');

        if($is_success == -1 || empty($trade_no)) {
            return response()->error('PARAM_EMPTY');
        }
        if($img->isFile()) {
            $path = '/face_cut';
            $file_name = date("YmdHis",time()).rand(1000,9999).".png";
            $path_ret=$path.'/'.$file_name;
            $img->storeAs('face_cut',$file_name,'public');
        }
        $cert_record = UserCertification::where('trade_no',$trade_no)->first();
        $cert_record->best_frame_path = $path_ret??'';
        $cert_record->status = $is_success;
        $cert_record->save();
        //判断男女
        $gender = 0;
        if(strlen($cert_record->id_card)==18) {
            $gender_flag = intval(substr($cert_record->id_card,16,1))%2;
            $gender=$gender_flag==1?1:2;
        }elseif(strlen($cert_record->id_card)==15){
            $gender_flag = intval(substr($cert_record->id_card,14,1))%2;
            $gender=$gender_flag==1?1:2;
        }
        //判断出生年月
        $year_m_str = substr($cert_record->id_card,6,8);
        $birth_day = substr($year_m_str,0,4).'-'.substr($year_m_str,4,2).'-'.substr($year_m_str,6,2);


        if($is_success==1) {
            $user_info = UserService::getById($uid);
            $user_info->name = $cert_record->name;
            $user_info->papers = $cert_record->id_card;
            $user_info->papers_type = 1;
            $user_info->is_auth = 1;
            $user_info->gender = $gender;
            $user_info->birth_at = $birth_day;
            $user_info->save();
            return response()->success($user_info);
        }
        return response()->success();
    }

    /**
     * 批量上传图片到服务器
     * @param Request $request
     * @return mixed
     */
    public function upload_img(Request $request) {
        $imgs = $request->allFiles();
        $imgs_return = array();
        foreach ($imgs as $img) {
            $path = '/upload';
            $file_name = date("YmdHis",time()).rand(1000,9999).".png";
            $path_ret=$path.'/'.$file_name;
            $img_path = public_path().$path_ret;

            $path_=$img->storeAs('upload',$file_name,'public');
            $imgs_return[] = env('APP_DOMAIN').$path_ret;

        }
        return response()->success($imgs_return);
    }


}